package com.hdl.service.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hdl.dao.MallOrderDao;
import com.hdl.dao.OrderDAO;
import com.hdl.dao.impl.MallOrderDaoImpl;
import com.hdl.dto.OrderSearch;
import com.hdl.entity.MallOrder;
import com.hdl.entity.MallOrderDetail;
import com.hdl.exception.CodeException;
import com.hdl.service.MallOrderService;
import com.hdl.util.JdbcUtil;
import com.hdl.vo.PageVO;

public class MallOrderServiceImpl implements MallOrderService{

	private static Logger log = LoggerFactory.getLogger(MallOrderServiceImpl.class);
	private MallOrderDao dao = new MallOrderDaoImpl();
	private OrderDAO orderdao = new OrderDAO();
	
	@Override
	public void saveOrder(MallOrder order) throws SQLException {
		Connection conn = JdbcUtil.getConnection();
		try {
			
			//采用事务的做法 传递连接对象
			
			//开启事务
			conn.setAutoCommit(false);
			
			//保存订单
			dao.saveOrder(conn,order);
			
			//保存订单详情
			for (MallOrderDetail detail  : order.getList()) {
				dao.saveOrderDetails(conn,detail);
			}
			
			conn.commit();//事务提交
			
			
		}catch(Exception e) {
			conn.rollback();//发生异常事务回滚
		}finally {
			conn.close();
			conn = null;//方便快速回收
		}
	}

	@Override
	public long countBySearch(OrderSearch search) throws CodeException {
		return 0;
	}

	@Override
	public PageVO<MallOrder> selectSearch(OrderSearch search, Integer current, Integer rowMax) throws CodeException {
		try {
			long total = orderdao.countBySearch(search);
			PageVO<MallOrder> page = new PageVO<MallOrder>(total, current, rowMax);
			page.setList(orderdao.selectSearch(search, page.getOffset(), page.getRowMax()));
			return page;
		} catch (SQLException e) {
			log.warn("获取订单分页数据失败",e);
			throw new CodeException(651, "获取订单分页数据失败",e);
		}
		
	}

	@Override
	public int updataStatus(String id, int status) throws CodeException {
		try {
			return orderdao.updataStatus(id, status);
		} catch (SQLException e) {
			log.warn("修改订单状态失败",e);
			throw new CodeException(651, "修改订单状态失败",e);
		}
	}
	public void UpdateOrderStatus2(String mallOrderId,Date payforTime) {
		dao.UpdateOrderStatus2(mallOrderId,payforTime);
	}

	@Override
	public List<MallOrder> findAllOrderByUserId(String hdlUserId, int orderStatus) {
		
		return dao.findAllOrderByUserId(hdlUserId,orderStatus);
	}

	@Override
	public MallOrder selectById(String mallOrderId) {
		
		return dao.selectById(mallOrderId);
	}

	@Override
	public void update(String mallOrderId, int i) {
		dao.update(mallOrderId,i);
	}

}
